package com.hengxinguotong.zhihuichengjian.ui.engineering.task;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.ServiceCompanyAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Company;
import com.hengxinguotong.zhihuichengjian.bean.CompanyListRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by liux on 2017/3/27.
 */

public class ServiceCompanyActivity extends BaseActivity {
    public static final int ALL = 1; //全部公司
    public static final int SERVICECOMPANY = 2;  //劳务公司 type=1或者2
    public static final int SERVICECOMPANYHASTEAM = 3; //人员不为空的劳务公司 type=1或者2
    public static final int COMMONSERVICECOMPANY = 4;  //type=2

    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.company_lv)
    PullToRefreshListView companyLv;
    @BindView(R.id.submit)
    HXTextView submit;
    private ServiceCompanyAdapter serviceCompanyAdapter;
    private int pageIndex = 1;
    private List<Company> companies;
    private int type = ALL;
    public static final int FROMTEAM = 1001;
    public static final int FROMPERSON = 1002;
    private int companyType = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_company);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", ALL);
        companyType = getIntent().getIntExtra("companyType", 0);
        companyLv.setMode(PullToRefreshBase.Mode.BOTH);
        companyLv.setRefreshing();
        companyLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (serviceCompanyAdapter != null) {
                    serviceCompanyAdapter.setSelect(position - 1);
                }
            }
        });
        companyLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getCompanyInfo(null);
            }
        });
        getCompanyInfo(getResources().getString(R.string.loading));
    }

    private void getCompanyInfo(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
//            jsonObject.put("pageNum", pageIndex);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = null;
        if(companyType == FROMTEAM){
            url = "/projectCompany/queryByConstructionId/";
        }else if(companyType == FROMPERSON){
            url = "/projectCompany/queryCompanyDetail/";
        }else{
            url = "/projectCompany/queryDetail/";
        }
        Utils.requestData(alert, this, url + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (companyLv.isRefreshing()) {
                    companyLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    CompanyListRes companyListRes = gson.fromJson(json, CompanyListRes.class);
//                    companyFilter(companyRes);//过滤公司类型
                    addData(companyListRes.getValue());
                }
            }

            @Override
            public void onFailure(String json) {
                if (companyLv.isRefreshing()) {
                    companyLv.onRefreshComplete();
                }
            }
        });
    }


    /**
     * 过滤租赁公司或者没有班组的公司
     *
     * @param companyListRes
     */
    private void companyFilter(CompanyListRes companyListRes) {
        List<Company> companies = companyListRes.getValue();
        Iterator<Company> companyIterator = companies.iterator();
        while (companyIterator.hasNext()) {
            Company company = companyIterator.next();
            switch (type) {
                case SERVICECOMPANY:
                    if (company.getType() == 3) {
                        companyIterator.remove();
                    }
                    break;
                case SERVICECOMPANYHASTEAM:
                    if (company.getType() == 3) {
                        companyIterator.remove();
                    } else if (company.getData() == null || company.getData().size() == 0) {
                        companyIterator.remove();
                    }
                    break;
                case COMMONSERVICECOMPANY:
                    if (company.getType() == 3 || company.getType() == 1) {
                        companyIterator.remove();
                    }
                    break;
            }
        }
    }

    private void addData(List<Company> datas) {
        if (pageIndex == 1) {
            if (datas.size() == 0) {
                showEmptyView(companyLv);
            } else {
                dismissEmptyView();
            }
            companies = datas;
            serviceCompanyAdapter = new ServiceCompanyAdapter(this, companies);
            companyLv.setAdapter(serviceCompanyAdapter);
            if (datas.size() == Utils.ONCECOUNT) {
                companyLv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
            }
        } else {
            companies.addAll(datas);
            serviceCompanyAdapter.notifyDataSetChanged();
        }

        if (datas.size() < Utils.ONCECOUNT) {
            companyLv.setMode(PullToRefreshBase.Mode.DISABLED);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

    @OnClick({R.id.iv_back, R.id.submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.submit:
                if (serviceCompanyAdapter != null) {
                    if (serviceCompanyAdapter.getSelect() == null) {
                        showToast("请选择劳务公司");
                    } else {
                        Intent intent = getIntent();
                        intent.putExtra("company", serviceCompanyAdapter.getSelect());
                        setResult(1, intent);
                        finish();
                    }
                }
                break;
        }
    }
}
